package com.ruoyi.equipment.apiController;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;

import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.equipment.domain.DrawerVo;
import com.ruoyi.equipment.domain.MqttVo;
import com.ruoyi.equipment.service.MqttRuleService;
import com.ruoyi.equipment.util.EmqxUtils;
import io.swagger.models.auth.In;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;


@RestController
@RequestMapping("/mqtt")
public class MqttRuleController extends BaseController {


    @Autowired
    private MqttRuleService mqttRuleService;

    @PostMapping("/returnDrawer")
    @Transactional(rollbackFor = Exception.class)
    public Integer rule(@RequestBody Map<String, Object> params) {

        //设备id 和 仓匣编号都是最新的
        String message = (String) params.get("payload");
        //解析字符串
        char c = message.charAt(0);
        if (c==123) {
            MqttVo mqttVo = JSONObject.parseObject(message, MqttVo.class);
            String userLogId = mqttVo.getUserLogId();
            String drawerId = mqttVo.getDrawerId();
            String equipmentId = mqttVo.getEquipmentId();
            String drawerNo = mqttVo.getDrawerNo();
            Integer code = mqttVo.getCode();
            //对设备进行归还操作
            if (code == 1) {
                //设备归还进行操作
                mqttRuleService.returnDrawer(drawerId, equipmentId, drawerNo);
            }
            if (code == 2) {
                //弹出失败 获得 之前的日志记录  将日志记录 修改 并打上备注 设备弹出失败 是已经归还过的 无需上传图片  修改仓匣状态
                mqttRuleService.popupError(userLogId, drawerId, equipmentId, drawerNo);
            }
        } else {

            //设备第一次连接 获取里面的内容
            ArrayList<MqttVo> mqttVoList = JSONObject.parseObject(message, new TypeReference<ArrayList<MqttVo>>() {
            });
            mqttRuleService.newConnectSet(mqttVoList);
        }

        return 0;
    }


    @PostMapping("/timer")
    public Integer timer(@RequestBody Map<String, Object> params){
        String message = (String) params.get("payload");
        ArrayList<DrawerVo> drawerVoList = JSONObject.parseObject(message, new TypeReference<ArrayList<DrawerVo>>() {
        });
         mqttRuleService.checkedDrawer(drawerVoList);
        return 0;
    }

}
